﻿using AiChiTu.TraceabilitySystem.Domain.AiChiTuManagement;
using AiChiTu.TraceabilitySystem.ErrorCode;
using AiChiTu.TraceabilitySystem.Infrastructure.Interfaces;
using AiChiTu.TraceabilitySystem.Write.API.Applications.Commands.Breedings;
using AutoMapper;
using MediatR;

namespace AiChiTu.TraceabilitySystem.Write.API.Applications.CommandsHandlers.Breedings
{
	/// <summary>
	/// 修改养殖信息请求命令处理
	/// </summary>
	public class UpdateBreedingCommandHandler : IRequestHandler<UpdateBreedingCommand, APIResult<bool>>
	{
		private readonly IBaseRepository<Breeding> breedingRepository;
		private readonly IMapper mapper;

		public UpdateBreedingCommandHandler(IBaseRepository<Breeding> breedingRepository, IMapper mapper)
		{
			this.breedingRepository = breedingRepository;
			this.mapper = mapper;
		}
		public async Task<APIResult<bool>> Handle(UpdateBreedingCommand request, CancellationToken cancellationToken)
		{
			APIResult<bool> result = APIResult<bool>.Result(ResultCode.UpdateFailed);

			Breeding? breeding = breedingRepository.QueryAllAsync(x => x.BreedingId == request.BreedingId).FirstOrDefault();
			if (breeding == null)
			{
				result.Message += " , 待修改的养殖信息不存在!";
				return await Task.FromResult(result);
			}
			breeding = mapper.Map(request, breeding);
			if (await breedingRepository.UpdateEntityAsync(breeding))
			{
				result = APIResult<bool>.Result(ResultCode.UpdateSuccess);
			}

			return await Task.FromResult(result);
		}
	}
}
